import { Image, StyleSheet, Text, View } from "react-native";
import React, { useEffect, useState } from "react";
import { DrawerMenu } from "./Drawer";
import { goodsDetail, goodsDetailColor, sizes } from "../types";
import { Https } from "../api";
import { AntDesign } from "@expo/vector-icons";
import { Button, Snackbar } from "react-native-paper";
import { styleAll } from "../styleAll";
import { useToast } from "react-native-toast-notifications";
import { useGetStoreString } from "../hooks/useStorage";
import { useNavigation } from "@react-navigation/native";

type CartPopupProps = {
  visible: boolean;
  hideModal: Function;
  goodsCode: string;
  gsColorCode: string;
  type?: string;
};

type goodsDetailInfo = {
  img: string;
  price: number;
  originalPrice: number;
  discount: number;
};
const CartPopup = ({
  visible,
  hideModal,
  goodsCode,
  gsColorCode,
  type,
}: CartPopupProps) => {
  const [goodsDetail, setGoodsDetail] = useState<goodsDetail>();
  const [goodsDetailInfo, setGoodsDetailInfo] = useState<goodsDetailInfo>();
  const [actionIndex, setActionIndex] = useState(0);
  const [actionSize, setActionSize] = useState(-1);
  const [goodsStock, setGoodsStock] = useState<object>({}) as any;
  const [sizeList, setSizeList] = useState<Array<sizes>>([]);
  const [colorList, setColorList] = useState<Array<goodsDetailColor>>([]);
  const [currentRepertory, setCurrentRepertory] = useState<number>(0);
  const [commodityCount, setCommodityCount] = useState<number>(1);
  const [projectCode, setProjectCode] = useState<string>("");
  const [show, setShow] = useState<boolean>(false);
  const [snackbarTitle, setSnackbarTitle] =
    useState<string>("已添加进您的购物车");
  const navigation = useNavigation();
  const toast = useToast();
  const onDismissSnackBar = () => setShow(false);
  useEffect(() => {
    visible && getGoodsDetail();
    return () => {
      setCurrentRepertory(0);
      setActionSize(-1);
      setCommodityCount(1);
    };
  }, [visible]);

  const jointImgUrl = (colorCode: string, projectCodes?: string) => {
    return `https://cdn.bestseller.com.cn/goodsImagePC/ONLY/${
      projectCodes || projectCode
    }/${colorCode}/240400/${colorCode}_p7.jpg`;
  };

  const getGoodsDetail = async () => {
    try {
      const result = await Promise.all([
        Https.goodsDetail({
          goodsCode,
        }),
        Https.goodsStock({
          goodsCode,
          type: 0,
        }),
      ]);
      result.forEach(({ success, data }, index) => {
        if (success) {
          if (!index) {
            const { color, projectCode } = data;
            console.log(data, "商品数据");
            setColorList(color);
            setProjectCode(projectCode);

            changeSelect(gsColorCode, color);
          }
          index ? setGoodsStock(data) : setGoodsDetail(data);
        }
      });
    } catch (error) {
      alert("商品信息获取失败" + error);
    }
  };

  const handleOption = (
    index: number,
    scene: string,
    colorCode?: string,
    sku?: string
  ) => {
    switch (scene) {
      case "color":
        changeSelect(colorCode || "", goodsDetail?.color);
        setActionIndex(index);
        setActionSize(-1);
        setCurrentRepertory(0);
        break;
      case "size":
        setCurrentRepertory(sku && goodsStock[sku]);
        setActionSize(index);

        break;
    }
    setCommodityCount(1);
  };

  const handleCommodityCount = (behavior: string) => {
    switch (behavior) {
      case "reduce":
        commodityCount !== 1 && setCommodityCount(commodityCount - 1);
        break;
      case "add":
        commodityCount < currentRepertory &&
          setCommodityCount(commodityCount + 1);
        break;
    }
  };

  const changeSelect = (
    gsColorCode: string,
    colorList: Array<goodsDetailColor> | undefined
  ) => {
    colorList &&
      colorList.forEach(
        (
          {
            colorCode,
            price,
            originalPrice,
            discount,
            sizes,
          }: goodsDetailColor,
          indexS: number
        ) => {
          if (colorCode === gsColorCode) {
            console.log(colorCode.slice(0, 9), "1111");
            console.log(jointImgUrl(colorCode));

            setGoodsDetailInfo({
              img: jointImgUrl(colorCode, colorCode.slice(0, 9) || ""),
              price,
              originalPrice,
              discount,
            });
            setSizeList([...sizes]);
            setActionIndex(indexS);
          }
        }
      );
  };

  const verifyInventory = (sku: string) => {
    return Boolean(goodsStock[sku]);
  };

  const shoppingCarAdd = async () => {
    if (actionSize < 0) {
      toast.show("请先选择尺码", {
        type: "normal",
        placement: "top",
      });
      return;
    }
    const token = await useGetStoreString("token");
    if (!token) {
      hideModal && hideModal();
      setTimeout(() => {
        navigation.navigate("Login");
        toast.show("请先登录", {
          type: "normal",
          placement: "bottom",
        });
      }, 100);

      return;
    }
    const { msg, succeed } = await Https.shoppingCarAdd({
      addPrice: goodsDetailInfo?.price,
      colorName: colorList[actionIndex].colorAlias,
      goodsCode,
      goodsName: goodsDetail?.goodsName,
      gsColorCode,
      gscPicmainPath: jointImgUrl(colorList[actionIndex].colorCode),
      quantity: commodityCount,
      sizeName: sizeList[actionSize].sizeAlias,
      crmId: "",
      goodsSku: "",
      gscPicmainId: "",
    });

    // hideModal && hideModal();
    setShow(true);
    setSnackbarTitle(succeed ? "已添加进您的购物车" : "添加购物车失败");
  };
  return (
    <DrawerMenu
      visible={visible}
      hideModal={hideModal}
      menuPosition="bottom"
      Height={"70%"}
    >
      <View style={{ flex: 1, alignItems: "center" }}>
        <Image
          style={styles.DrawerMenuImg}
          // resizeMethod={"scale"}
          source={{
            uri: goodsDetailInfo?.img,
          }}
        />
        <Text style={styles.DrawerMenuTitle} numberOfLines={1}>
          {goodsDetail && goodsDetail?.goodsName}
        </Text>
        <View style={styles.DrawerMenuPriceMain}>
          <Text style={styles.DrawerMenuPrice}>￥{goodsDetailInfo?.price}</Text>
          {goodsDetailInfo?.discount !== 1 && (
            <Text style={styles.discount}>
              ￥{goodsDetailInfo?.originalPrice}
            </Text>
          )}
        </View>

        <View style={styles.DrawerMenuColorOption}>
          {colorList &&
            colorList.map(({ colorAlias, colorCode }, index) => (
              <Text
                style={
                  actionIndex === index
                    ? {
                        ...styles.DrawerMenuColorItem,
                        ...styles.actionBackground,
                      }
                    : styles.DrawerMenuColorItem
                }
                key={colorAlias}
                onPress={() => {
                  handleOption(index, "color", colorCode);
                }}
              >
                {colorAlias}
              </Text>
            ))}
        </View>
        <View style={{ ...styles.DrawerMenuColorOption, marginTop: 10 }}>
          {sizeList &&
            sizeList.map(({ sizeAlias, sku }, index) => (
              <Text
                style={
                  verifyInventory(sku)
                    ? actionSize === index
                      ? {
                          ...styles.DrawerMenuColorItem,
                          ...styles.actionBackground,
                        }
                      : styles.DrawerMenuColorItem
                    : { ...styles.DrawerMenuColorItem, color: "#ccd0db" }
                }
                onLayout={() => {
                  setCurrentRepertory(() => currentRepertory + goodsStock[sku]);
                }}
                key={sku}
                onPress={() => {
                  verifyInventory(sku) && handleOption(index, "size", "", sku);
                }}
              >
                {sizeAlias}
              </Text>
            ))}
        </View>

        <View style={styles.stepUnit}>
          <View style={styles.stepUnitMain}>
            <AntDesign
              name="minuscircle"
              size={20}
              color="black"
              onPress={() => handleCommodityCount("reduce")}
            />
            <Text>{String(commodityCount)}</Text>
            <AntDesign
              name="pluscircle"
              size={20}
              color="black"
              onPress={() => handleCommodityCount("add")}
            />
          </View>

          <Text style={styles.stepUnitText}>
            库存：{String(currentRepertory)}
          </Text>
        </View>

        <View style={{ ...styles.bottomAdd }}>
          <Button
            mode="contained"
            textColor="#fff"
            buttonColor="#000"
            labelStyle={{ fontSize: 17 }}
            style={{ borderRadius: 0 }}
            contentStyle={{
              ...styles.bottomAddButton,
              ...styleAll.iosButtonBottom,
            }}
            onPress={() => shoppingCarAdd()}
          >
            {type === "addCart" ? "加入购物车" : "立即购买"}
          </Button>
        </View>
        <Snackbar
          visible={show}
          duration={4000}
          onDismiss={onDismissSnackBar}
          action={{
            label: "关闭",
            onPress: () => {},
          }}
        >
          {snackbarTitle}
        </Snackbar>
      </View>
    </DrawerMenu>
  );
};

export default CartPopup;

const styles = StyleSheet.create({
  DrawerMenuImg: {
    height: 150,
    width: 90,
  },
  DrawerMenuTitle: {
    paddingTop: 10,
    paddingHorizontal: 30,
    fontSize: 16,
    fontWeight: "600",
  },
  DrawerMenuPriceMain: {
    width: 130,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-evenly",
    paddingVertical: 10,
  },
  DrawerMenuPrice: {
    // paddingRight:20,
    fontSize: 16,
    fontWeight: "600",
    color: "#ff3333",
  },
  discount: {
    textDecorationLine: "line-through",
    color: "#929090",
    fontSize: 16,
  },
  DrawerMenuColorOption: {
    width: "100%",
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "space-evenly",
    paddingHorizontal: 20,
    border: "solid",
    borderColor: "#000",
  },
  DrawerMenuColorItem: {
    marginTop: 15,
    paddingHorizontal: 5,
    paddingVertical: 3,
    backgroundColor: "#fff",
    color: "#000",
  },
  actionBackground: {
    backgroundColor: "#000",
    color: "#fff",
  },
  stepUnit: {
    display: "flex",
    flexDirection: "row",
    height: 50,
    marginTop: 10,
  },
  stepUnitMain: {
    display: "flex",
    flexDirection: "row",
    justifyContent: "space-evenly",
    alignItems: "center",
    flex: 0.5,
    // border: 1,
    borderTopColor: "#ccc",
  },
  stepUnitText: {
    flex: 0.5,
    textAlign: "center",
    lineHeight: 50,
  },
  bottomAdd: {
    position: "absolute",
    bottom: 0,
    width: "100%",
  },
  bottomAddButton: {
    width: "100%",
    borderRadius: 0,
  },
});
